import React, { Component } from 'react';
import { connect } from 'dva';
// import { Tabs } from 'antd';
import styles from './index.css';
import sty from '../statistics/components/deviceComponents/commList.css';
// const { TabPane } = Tabs;
import { createHashHistory } from 'history';
import { Select, Button, DatePicker, Spin, message } from 'antd';
import _ from 'lodash';
import { Dispatch, AnyAction } from 'redux';
import locale from 'antd/lib/date-picker/locale/zh_CN';
import moment from 'moment';
import { QueryLogDeviceStatisVo, QueryLogDeviceVoList } from '@/models/connect';
import {
  logDeviceStatisVo,
  queryByDeviceType,
  logDeviceList,
  logdeviceAlamList,
  logDeviceStateList,
} from '@/services/journalManage';
import { RESPONSE_SUCCESS, RESPONSE_FAIL } from '@/const';
import { debug } from 'webpack';
import produce, { Draft } from 'immer';
import { getDictDataList } from '@/services/systemDevice';
import { isMenuVisible } from '@/utils/utils';
// import { Item } from 'rc-menu';

moment.locale('zh-cn');
const { Option } = Select;

interface DevicelogProps {
  logDeviceStatisVo?: QueryLogDeviceStatisVo;
  loading?: boolean;
  dispatch: Dispatch<AnyAction>;
}
class devicelog extends Component<DevicelogProps> {
  constructor(props: DevicelogProps) {
    super(props);
    this.state = {
      lastScrollSite: '',
      presentPageNum: 1,
      startValue: null,
      endValue: null,
      loading: true,
      logType: '1',
      parameters: {
        startTime: null,
        endTime: null,
        pageNum: '1',
        pageSize: '10',
      },
      detailsData: [],
      tableData: {},
      pageTotal: '',
    };
  }
  handleLoading = async () => {
    const { dispatch } = this.props;
    this.setState({
      loading: true,
    });
    let [err, data] = await logDeviceStatisVo(this.state.parameters);
    if (!err) {
      this.setState({
        tableData: data,
      });
    }
    isMenuVisible('iot:deviceLog:list') && this.handleFilterQuery();
  };
  handleFilterQuery = async () => {
    // 搜索
    const { dispatch } = this.props;
    this.setState({
      loading: true,
    });
    if (this.state.logType == 1) {
      //设备报警
      let [err, data] = await logdeviceAlamList(this.state.parameters);
      if (!err) {
        const logDeviceVoList1 = data.rows;
        if (logDeviceVoList1 != null && logDeviceVoList1.length != 0) {
          //设备报警
          logDeviceVoList1.map(item => {
            const date1 = moment(item.createTime).format('HH:mm:ss');
            const date2 = moment(item.createTime).format('YYYY-MM-DD');
            let logText;
            let deleteFalgName;
            if (item.deleteFalg == 1) {
              deleteFalgName = '已删除';
            } else {
              deleteFalgName = '未删除';
            }
            let processStateName;
            if (item.processState == 0) {
              processStateName = '待处理';
            } else if (item.processState == 1) {
              processStateName = '已处理';
            } else {
              processStateName = '处理失败';
            }
            logText =
              item.happenTime +
              '，设备编号：' +
              item.deviceId +
              '，报警类型：' +
              item.alamTypeName +
              '，报警内容：' +
              item.alamContent +
              '，删除状态：' +
              deleteFalgName +
              '，处理状态：' +
              processStateName +
              '，报警截图：' +
              item.alamImg +
              '，备注：' +
              item.remarks;

            let itemdata = {
              text: logText,
              id: item.logDeviceId,
              date: date2,
              time: date1,
            };
            this.setState({
              detailsData: [...this.state.detailsData, itemdata],
              pageTotal: data.total,
            });
          });
        } else {
          message.info('查询已结束');
        }
      }
    } else if (this.state.logType == 2) {
      //设备状态
      let [err, data] = await logDeviceStateList(this.state.parameters);
      if (!err) {
        const logDeviceVoList1 = data.rows;
        if (logDeviceVoList1 != null && logDeviceVoList1.length != 0) {
          //设备状态
          logDeviceVoList1.map(async item => {
            const date1 = moment(item.createTime).format('HH:mm:ss');
            const date2 = moment(item.createTime).format('YYYY-MM-DD');
            let logText;
            //请求设备类型
            let deviceTypeNo = item.deviceTypeNo;
            let param = { deviceTypeNo };
            let [err, data] = await queryByDeviceType(param);
            let deviceTypeName = data.deviceTypeName;
            let deviceStateName;
            if (item.deviceState == 1) {
              deviceStateName = '正常';
            } else {
              deviceStateName = '异常';
            }
            logText =
              item.createTime +
              '，设备编号：' +
              item.deviceId +
              '，设备类型：' +
              deviceTypeName +
              '，设备名称：' +
              item.deviceName +
              '，设备状态：' +
              deviceStateName +
              '，类型名称：' +
              item.typeName +
              '，状态：' +
              item.stateName;

            let itemdata = {
              text: logText,
              id: item.logDeviceId,
              date: date2,
              time: date1,
            };
            this.setState({
              detailsData: [...this.state.detailsData, itemdata],
              pageTotal: data.total,
            });
          });
        } else {
          message.info('查询已结束');
        }
      }
    }
    this.setState({
      loading: false,
    });
  };

  componentDidMount() {
    const scrollDiv = document.getElementById('scroll_div'); //js的写法 上面的和这个选择一个
    const offsetHeight = scrollDiv.offsetHeight;
    //绑定事件
    scrollDiv.addEventListener('scroll', () => {
      const scrollTop = scrollDiv.scrollTop;
      const scrollHeight = scrollDiv.scrollHeight;
      if (offsetHeight + scrollTop >= scrollHeight) {
        //触发事件
        const count = this.state.presentPageNum;

        this.setState(
          produce((draft: Draft): void => {
            draft.parameters.pageNum = count + 1;
            draft.presentPageNum = count + 1;
            draft.lastScrollSite = scrollHeight;
          }),
        );
        let arrylist = [];
        arrylist = this.state.detailsData;
        if (arrylist.length != this.state.pageTotal) {
          isMenuVisible('iot:deviceLog:list') && this.handleFilterQuery();
        }
      }
    });
    this.handleLoading();
  }
  handleTabChange = (type: string) => {
    // console.log(type);
  };
  handleChange = (value: string) => {
    this.setState(
      produce((draft: Draft): void => {
        draft.logType = value;
      }),
      () => {},
    );
  };
  handleStartOpenChange = (value: any | null, dateString: any) => {
    this.setState(
      produce((draft: Draft): void => {
        draft.parameters.startTime = dateString;
        draft.startValue = dateString;
      }),
    );
  };

  handleEndOpenChange = (value: any | null, dateString: any) => {
    this.setState(
      produce((draft: Draft): void => {
        draft.parameters.endTime = dateString;
        draft.endValue = dateString;
      }),
    );
  };
  handleQuery = () => {
    this.setState(
      produce((draft: Draft): void => {
        draft.parameters.pageNum = '1';
        draft.detailsData = [];
      }),
      () => {
        isMenuVisible('iot:deviceLog:list') && this.handleFilterQuery();
      },
    );
  };
  render() {
    // const { logDeviceStatisVo = {}, logDeviceVoList = [] } = this.props;
    return (
      <div className={styles['log-container']}>
        {(
          <Spin spinning={this.state.loading}>
            <div className={styles['log-con-top']}>
              <div className={styles['log-con-top-box']}>
                <p>今日</p>
                <div className={styles['log-con-top-box-tBox']}>
                  <span>{this.state.tableData.dayCount}</span>
                </div>
              </div>
              <div className={styles['log-con-top-box']}>
                <p>近一周</p>
                <div className={styles['log-con-top-box-tBox']}>
                  <span>{this.state.tableData.weekCount}</span>
                </div>
              </div>
              <div className={styles['log-con-top-box']}>
                <p>近30天</p>
                <div className={styles['log-con-top-box-tBox']}>
                  <span>{this.state.tableData.monthCount}</span>
                </div>
              </div>
            </div>

            <div className={styles['log-con-bottom']}>
              <div className={sty['inforAnasy-container-top-input dev-search marginBom']}>
                <div className={styles['dev-search-select']}>
                  <span className={styles['dev-search-select-title']}>日志类型</span>
                  <Select
                    // defaultValue="1"
                    value={this.state.logType}
                    style={{ width: 200 }}
                    onChange={this.handleChange}
                  >
                    <Option value="1">设备报警</Option>
                    <Option value="2">设备状态</Option>
                  </Select>
                </div>
                <div className={styles['dev-search-select']}>
                  <span className={styles['dev-search-select-title']}>日志开始时间</span>
                  {/* value={this.state.startValue} */}
                  <DatePicker
                    defaultPickerValue={this.state.startTime}
                    // value={this.state.startTime}
                    value={
                      this.state.parameters.startTime
                        ? moment(this.state.parameters.startTime)
                        : undefined
                    }
                    onChange={this.handleStartOpenChange}
                    locale={locale}
                  />
                </div>
                <div className={styles['dev-search-select']}>
                  <span className={styles['dev-search-select-title']}>日志结束时间</span>
                  {/* value={this.state.endValue} */}
                  <DatePicker
                    defaultPickerValue={this.state.endValue}
                    // value={this.state.endValue}
                    value={
                      this.state.parameters.endTime
                        ? moment(this.state.parameters.endTime)
                        : undefined
                    }
                    onChange={this.handleEndOpenChange}
                    locale={locale}
                  />
                </div>
                <Button type="link" className={styles['search']} onClick={this.handleQuery}>
                  搜索
                </Button>
                <Button
                  className={styles['search']}
                  type="link"
                  size="large"
                  onClick={() => {
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.logType = '1';
                        draft.parameters.endTime = null;
                        draft.endValue = null;
                        draft.parameters.startTime = null;
                        draft.startValue = null;
                      }),
                      () => {},
                    );
                  }}
                >
                  重置
                </Button>
              </div>
              <div id="scroll_div" className={styles['details']}>
                <div className={styles['details-box']}>
                  {_.map(this.state.detailsData, item => (
                    <div className={styles['details-box-tBox']} key={item.id}>
                      <div className={styles['textBox-right']}>{item.text}</div>
                      <div className={styles['textBox-left']}>
                        <p>{item.date}</p>
                        <span>{item.time}</span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </Spin>
        )}
      </div>
    );
  }
}

export default connect(({ loading, journalManageMode }: any) => ({
  loading: loading.effects['journalManageMode/logDeviceStatisVo'],
  logDeviceStatisVo: journalManageMode.logDeviceStatisVo,
  logDeviceVoList: journalManageMode.logDeviceVoList,
}))(devicelog);
